import { ChangeEvent, useEffect, useState } from "react";
import styles from "./login.module.scss";
import initLoginBg from "./init.ts";
import { Input, Space, Button, message } from "antd";
import "./login.less";
import { CaptchaAPI, LoginAPI } from "@/request/api";
import { useNavigate } from "react-router-dom";

const view = () => {
  // 加载完组件之后，执行：加载背景
  // 第二个参数是空数组，则仅在组件第一次挂载ui时调用
  useEffect(() => {
    getCaptchaImg();
    initLoginBg();
    window.onresize = function () {
      initLoginBg();
    };
  }, []);

  let navigateTo = useNavigate();
  const [userNameVal, setUserName] = useState("");
  const [passwordVal, setPassword] = useState("");
  const [captchaVal, setCaptchaVal] = useState("");
  //验证码图片
  const [captchaImg, setCaptchaImg] = useState("");
  // 获取输入的用户名
  const userNameChange = (e: ChangeEvent<HTMLInputElement>) => {
    setUserName(e.target.value);
  };
  const passWordChange = (e: ChangeEvent<HTMLInputElement>) => {
    setPassword(e.target.value);
  };
  const captchaChange = (e: ChangeEvent<HTMLInputElement>) => {
    setCaptchaVal(e.target.value);
  };
  const gotoLogin = async () => {
    if (!userNameVal.trim() || !passwordVal.trim() || !captchaVal.trim()) {
      message.warning("请输入完整用户名、密码、验证码!");
      return;
    }
    let LoginAPIRes: any = await LoginAPI({
      username: userNameVal,
      password: passwordVal,
      code: captchaVal,
      uuid: localStorage.getItem("uuid"),
    });
    if (LoginAPIRes.code === 200) {
      // 1.提示登陆成功
      message.open({
        type: "success",
        content: "登录成功!",
      });
      // 2.保存token
      localStorage.setItem("react-token", LoginAPIRes.uuid);
      // 3.跳转到/page1
      navigateTo("/page1");
      // 4.删除uuid
      localStorage.removeItem("uuid");
    } else {
      message.warning(LoginAPIRes.msg);
    }
  };
  // 获取验证码图片
  const getCaptchaImg = async () => {
    // 1.回显验证码图片 2.保存uuid登录用
    let captchaAPIRes = await CaptchaAPI();
    if (captchaAPIRes.code === 200) {
      setCaptchaImg("data:image/gif;base64," + captchaAPIRes.img);
      localStorage.setItem("uuid", captchaAPIRes.uuid);
    }
  };

  return (
    <div className={styles["loginPage"]}>
      {/* 存放背景 */}
      <canvas id="canvas" style={{ display: "block" }}></canvas>
      {/* <p>登录页</p> */}
      {/* 登录盒子 */}
      <div className={styles.loginBox + " loginbox"}>
        {/* 标题部分 */}
        <div className={styles.title}>
          <h1>React&nbsp;·&nbsp;通用后台系统</h1>
          <p>Strive Everyday</p>
        </div>
        {/* 表单部分 */}
        <div className="form">
          <Space direction="vertical" size="large" style={{ display: "flex" }}>
            <Input placeholder="Basic Usage" onChange={userNameChange} />
            <Input.Password
              placeholder="Input Password"
              onChange={passWordChange}
            />
            <div className="captchaBox">
              <Input placeholder="Verification Code" onChange={captchaChange} />
              {/* 验证码 */}
              <div className="captchaImg" onClick={getCaptchaImg}>
                <img height="38" src={captchaImg} alt="" />
              </div>
            </div>
            <Button
              onClick={gotoLogin}
              className="loginBtn"
              type="primary"
              block
            >
              登录
            </Button>
          </Space>
        </div>
      </div>
    </div>
  );
};
export default view;
